package com.wyzt.auth.web;

import com.wyzt.auth.config.JwtProperties;
import com.wyzt.auth.entiy.UserInfo;
import com.wyzt.auth.service.AuthService;
import com.wyzt.auth.utils.JwtUtils;
import com.wyzt.common.enums.ExceptionEnum;
import com.wyzt.common.exception.WyztException;
import com.wyzt.common.utils.CookieUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RestController
@EnableConfigurationProperties(JwtProperties.class)
public class AuthController {
    @Autowired
    private AuthService authService;
    @Autowired
    private JwtProperties jwtProp;

    /**
     * 登陆授权
     *
     * @param username
     * @param password
     * @return
     */
    @PostMapping("login")
    public ResponseEntity<Void> login(
            @RequestParam("username") String username,
            @RequestParam("password") String password,
            HttpServletRequest request,
            HttpServletResponse response
    ) {
        String token = authService.login(username, password);
        CookieUtils.setCookie(
                request, response,
                jwtProp.getCookieName(), token,
                jwtProp.getCookieMaxAge(), null, true);
        return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
    }

    /**
     * 校验用户登陆状态
     *
     * @param token
     * @return
     */
    @GetMapping("verify")
    public ResponseEntity<UserInfo> verify(@CookieValue("WYZT_TOKEN") String token,
                                           HttpServletRequest request,
                                           HttpServletResponse response) {
        //解析token
        try {
            UserInfo userInfo = JwtUtils.getInfoFromToken(token, jwtProp.getPublicKey());
            //刷新token
            String newToken = JwtUtils.generateToken(
                    userInfo,
                    jwtProp.getPrivateKey(),
                    jwtProp.getExpire());
            CookieUtils.setCookie(
                    request, response,
                    jwtProp.getCookieName(), newToken,
                    jwtProp.getCookieMaxAge(), null, true);
            return ResponseEntity.ok(userInfo);
        } catch (Exception e) {
            //token已过期或者token被纂改
            throw new WyztException(ExceptionEnum.UNAUTHORIZED);
        }
    }
}
